//
//  82. 删除排序链表中的重复元素II.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/9/5.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution82 {
    // 删除排序链表中的重复元素
    func deleteDuplicates(_ head: ListNode?) -> ListNode? {
        let vHead = ListNode(-1)
        vHead.next = head
        var pre: ListNode? = vHead
        var cur = head
        while cur != nil {
            var curNext = cur?.next
            // 只要相等，就一直向下找
            var hadDup = false
            while cur!.val == curNext?.val {
                hadDup = true
                curNext = curNext?.next
            }
            if hadDup {
                // 有重复的，直接删掉，pre指针不变
                pre?.next = curNext
            } else {
                // 没有重复的，调整pre指针
                pre = cur
            }
            cur = curNext
        }
        return vHead.next
    }
    static func test() {
        let node1 = ListNode(1)
        let node2 = ListNode(2)
        let node3 = ListNode(3)
        let node33 = ListNode(3)
        let node4 = ListNode(4)
        let node44 = ListNode(4)
        let node5 = ListNode(5)
        
        node1.next = node2
        node2.next = node3
        node3.next = node33
        node33.next = node4
        node4.next = node44
        node44.next = node5
        
        let solution = Solution82()
        let result = solution.deleteDuplicates(node1)
        print(result)
    }
}
